package com.itxiuyixiu.homework.security.config;

import com.itxiuyixiu.homework.security.handler.ApiAuthenticationFailureHandler;
import com.itxiuyixiu.homework.security.handler.ApiAuthenticationSuccessHandler;
import com.itxiuyixiu.homework.security.service.AdminDetailsServiceImpl;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;

/**
 * @author 黄磊
 * @date 2020/3/6
 */
@Order(1)
@Component
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AdminDetailsServiceImpl adminDetailsService;

    private final String adminContextPath;

    public AdminSecurityConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(adminDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String hostAddress = Inet4Address.getLocalHost().getHostAddress();
        String s = String.format("hasIpAddress('%s')", hostAddress);
        System.out.println(s);

        http.antMatcher("/admin/**")
                .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/admin/login")
                .successHandler(new ApiAuthenticationSuccessHandler())
                .failureHandler(new ApiAuthenticationFailureHandler())
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/admin/logout")
                .logoutSuccessUrl("/admin/login.html")
                .and()
                .authorizeRequests()
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers("/admin/monitor/client/**").access(s)
                .anyRequest().hasRole("ADMIN")
                .and().httpBasic()
                .and().csrf().disable().cors(Customizer.withDefaults());
    }
}
